<template>
  <div style="margin: 20px 20px">
    <el-tree
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps">
      </el-tree>
    <el-button :disabled="saveBtnDisabled" type="primary" @click="save">保存</el-button>
  </div>
</template>
<script>
import menu from '@/api/acl/menu'

export default {
  data() {
    return {
      saveBtnDisabled:false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleId:''

    };
  },
  // 监听器
  watch: {
    $route(to, from) {
      console.log('路由变化......')
      console.log(to)
      console.log(from)
      this.init()
    }
  },

  created () {
    this.init()
  },
  methods: {

    init(){
      // 存在参数则获取角色绑定的权限
      if (this.$route.params && this.$route.params.id) {
          this.roleId = this.$route.params.id
          this.fetchDataById(this.roleId)
      } 
    },
    // 获取角色绑定的权限
    fetchDataById(roleId){
        menu.toAssign(roleId).then(response => {
            this.data = response.data.permissionList
            console.log("permission权限集合 == ",this.data)
            //需要将角色已经拥有的权限选出来  =》 展示
            let list = [];
            this.findCheckedNode(this.data[0].children,list)
            console.log("最终集合",list)
            //进行展示
            this.setCheckedKeys(list)
        })
    },
    //返回已经选中的数据 [1,2,3...]
    findCheckedNode(data,list){
      for(let i = 0;i<data.length;i++){
        if(data[i]['select'] == true && data[i]['level'] == 3){
          list.push(data[i]['id'])
        }
        if(data[i]['children'] != null){ 
          this.findCheckedNode(data[i]['children'],list)
        } 
      }
      return list;
    },
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes());
    },
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys());
    },
    //数据展示
    setCheckedKeys(list) {
      this.$refs.tree.setCheckedKeys(list);
    },

    save(){
      // 设置已经点击保存，不可再次点击
      this.saveBtnDisabled = true
      // 返回选中的节点
      var ids = this.$refs.tree.getCheckedKeys();
      // 返回选中的父节点
      var parentIds = this.$refs.tree.getHalfCheckedKeys();
      for(let i = 0;i<parentIds.length;i++){
        ids.push(parentIds[i]);
      }
      console.log("权限的id == ",ids);
      //vue elementUI tree树形控件获取父节点ID的实例
      //25348行修改源码
      menu.doAssign(this.roleId, ids).then(response => {
          if(response.success){
              this.$message({
                type:'success',
                message:'保存成功'
              })
              this.$router.push({ path: '/acl/role/list' })
            }
      })
    }
  }
};
</script>
